//
//  BusinessReleaseDetailsCell.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/7/21.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "BusinessReleaseDetailsCell.h"
#import "WGBSelectPhotoView.h"
#import "SDPhotoBrowser.h"

#define kMaxSelectImagesCount 9
@interface BusinessReleaseDetailsCell ()<WGBSelectPhotoViewDelegate,UITextViewDelegate,SDPhotoBrowserDelegate>
@property (nonatomic,strong) WGBSelectPhotoView *selectPhotoView;
@property (strong, nonatomic)NSMutableArray *selectImageArray;
@property (assign, nonatomic)int loadIndex;

@end
@implementation BusinessReleaseDetailsCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.selectPhotoView = [[WGBSelectPhotoView alloc]init];
    self.selectPhotoView.frame = CGRectMake(0, 200, kScreenW, 300);
    self.selectPhotoView.rowCount = 3;
    [self.selectPhotoView showAddButtonDisplay];
    self.selectPhotoView.delegate = self;
    [self.contentView addSubview:self.selectPhotoView];
    self.contentTF.delegate = self;
    
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    self.contentLabel.hidden = YES;
    
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    if (textView.text.length == 0) {
        self.contentLabel.hidden = YES;
    }else {
        self.contentLabel.hidden = NO;
    }
    
}

- (void)setModel:(BusinessJobModel *)model {
    
    _model = model;
    self.titleTF.text = model.recruit_name;
    self.contentTF.text = model.descriptionText;
    if (self.contentTF.text.length > 0) {
        self.contentLabel.hidden = YES;
    }
    self.selectImageArray = [NSMutableArray array];
    NSMutableArray *itemList = [NSMutableArray array];
    self.loadIndex = 0;
    for (NSDictionary *dict in model.picture_list) {
        NSString *path = dict[@"path"];
        SDWebImageManager *manager = [SDWebImageManager sharedManager] ;
        [manager loadImageWithURL:[NSURL URLWithString:path] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (finished) {
                WGBSelectPhotoDataItem *item = [WGBSelectPhotoDataItem new];
                item.coverImage = image;
                [itemList addObject:item];
                [self.selectImageArray  addObject:image];
                [self.selectImagePathArray addObject:path];
                if (self.loadIndex == model.picture_list.count - 1) {
                    [self.selectPhotoView addPhotoesWithDataItems:itemList];
                }
                self.loadIndex += 1;
            }
            
            
        }];
    }
   
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)uploadHeadImage:(NSArray *)tempPhotoes {
    __weak typeof(self) weakSelf = self;
   
    [NetManager isUpdateImgArr:tempPhotoes andData:nil andFileName:nil success:^(NSDictionary *dic) {
       
        NSString *imagePath = dic[@"object"];
        if (tempPhotoes.count > 1) {
            NSArray *pathS = [imagePath componentsSeparatedByString:@","];
            [self.selectImagePathArray addObjectsFromArray:pathS];

        }else {
            [self.selectImagePathArray addObject:imagePath];
        }

    } uploadProgress:^(NSProgress *_Nonnull str) {
        
    }];
}

///MARK:- <WGBSelectPhotoViewDelegate>
- (void)wgb_photoViewDidClickedPhotoAtIndex:(NSInteger)index
                                  photoView:(WGBSelectPhotoView *)photoView{

    if (index == [self.selectPhotoView picturesCount]) {
        [self selectPhoto];
    }else {
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        browser.currentImageIndex = index;
        
        browser.imageCount = self.selectImagePathArray.count;
        browser.delegate = self;
        [browser show];
    }
}

#pragma mark - SDPhotoBrowserDelegate
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    
    return [NSURL URLWithString:self.selectImagePathArray[index]];
}

//删除图片事件回调
- (void)wgb_photoViewDidDeletedPhotoAtIndex:(NSInteger)index
                                  photoView:(WGBSelectPhotoView *)photoView{
    if (self.selectImageArray.count) {
        [self.selectImageArray removeObjectAtIndex: index];
        [self.selectImagePathArray removeObjectAtIndex: index];
    }
    
}

//移动图片事件
- (void)wgb_photoViewDidMovedPhotoWithStartIndex:(NSInteger)startIndex
                                        endIndex:(NSInteger)endIndex
                                       photoView:(WGBSelectPhotoView *)photoView{
    if (startIndex != endIndex) {
        NSMutableArray *tempArr = self.selectImageArray.mutableCopy;
        id startObj = tempArr[startIndex];
        ///MARK:- 此处是简单的插入排序算法的运用
        if (startIndex > endIndex) {
            [tempArr insertObject:startObj atIndex:endIndex];
            [tempArr removeObjectAtIndex:startIndex+1];
        }else{
            [tempArr insertObject:startObj atIndex:endIndex+1];
            [tempArr removeObjectAtIndex:startIndex];
        }
        self.selectImageArray = tempArr;
    }
    
}


///MARK:- 选择照片
- (void)selectPhoto{
    TZImagePickerController *pickerVC = [[TZImagePickerController alloc] init];
    pickerVC.allowPickingVideo = NO;
    pickerVC.allowPickingMultipleVideo = NO;//多选
    pickerVC.maxImagesCount = kMaxSelectImagesCount; //其实这样 kMaxSelectImagesCount - self.selectImageArray.count 就完事儿了 可我就是不想改
    pickerVC.statusBarStyle = UIStatusBarStyleLightContent;
    [[CommonTTool getCurrentVC] presentViewController:pickerVC animated:YES completion:^{
        
    }];
        
    [pickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (self.selectImageArray.count + assets.count > kMaxSelectImagesCount) {
            [self outOfLimitAlertTips];
        }
        
        ///MARK：- 优雅的方式 只获取`kMaxSelectImagesCount`张
        if (self.selectImageArray.count) {
            NSInteger detaCount = kMaxSelectImagesCount - self.selectImageArray.count;
            detaCount = MIN(detaCount, assets.count);
            NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:
                                   NSMakeRange(0,detaCount)];
            NSArray *tempAssets = [assets objectsAtIndexes:indexes];
            NSArray *tempPhotoes = [photos objectsAtIndexes:indexes];
            NSArray<WGBSelectPhotoDataItem *> *items = [WGBSelectPhotoDataItem createDataItemsWithPHAssets:tempAssets photoes:tempPhotoes];
            [self.selectPhotoView addPhotoesWithDataItems:items];
            [self.selectImageArray addObjectsFromArray:photos];
            [self uploadHeadImage:photos];
        }else{
            NSArray<WGBSelectPhotoDataItem *> *items = [WGBSelectPhotoDataItem createDataItemsWithPHAssets:assets photoes:photos];
            [self.selectPhotoView addPhotoesWithDataItems:items];
            [self.selectImageArray addObjectsFromArray:photos];
            [self uploadHeadImage:photos];

        }
    }];
}

///MARK:- 超出限制提示信息
- (void)outOfLimitAlertTips{
    NSString *message = [NSString stringWithFormat:@"最多只能选择%ld个媒体资源",(long)kMaxSelectImagesCount];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction: action];
    [[CommonTTool getCurrentVC] presentViewController:alert animated:YES completion:nil];
}

- (NSMutableArray *)selectImagePathArray {
    
    if (!_selectImagePathArray) {
        _selectImagePathArray = [NSMutableArray array];
    }
    return _selectImagePathArray;
}

@end
